/**
 * @author scylla
 * @version V1.0
 * @Project echo-java-base
 * @Title 原子类
 * @Description *
 * @Package concurrent.mthread.automicclass
 * @Since 2021/8/18 11:41 上午
 */
package concurrent.mthread.automicclass;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerTest implements Runnable {

    private AtomicInteger i = new AtomicInteger(0);

    public int getValue() {
        return i.get();
    }

    public void evenIncrement() {
        //原子自增2
        i.addAndGet(2);
    }

    @Override
    public void run() {
        //无限自增
        for (; ; ) evenIncrement();
    }


    public static void main(String[] args) {
        //创建一个 定时任务。  5s 后结束
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("定时任务到时,自动退出");
                System.exit(0);
            }
        }, 5000);


        //启动自增任务
        ExecutorService exec = Executors.newCachedThreadPool();
        AtomicIntegerTest ait = new AtomicIntegerTest();
        exec.execute(ait);
        for (; ; ) {
            int j = ait.getValue();
            if (j % 2 != 0) {
                //奇数退出
                System.out.println("产生奇数:" + j);
                System.exit(0);
            }
        }
    }


}
